package com.neusoft.hifly.rpc.message.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.core.pojo.ApiCode;
import com.neusoft.hifly.core.pojo.ApiResponse;
import com.neusoft.hifly.rpc.message.dao.IMessageDao;
import com.neusoft.hifly.rpc.message.domain.MsgDTO;
import com.neusoft.hifly.rpc.message.domain.MsgUserVO;
import com.neusoft.hifly.rpc.message.service.IMessageService;

/**
 * Title: 消息服务
 * <p>
 * Description: 消息服务接口
 * <p>
 * Copyright: Copyright (c) 2008
 * <p>
 * Company: 东软汉枫
 *
 * @author lihui
 * @version 1.0.0
 */
@Service
public class MessageServiceImpl implements IMessageService {

	@Autowired(required = false)
	private IMessageDao messageDao;

	/**
	 * 发送消息
	 *
	 * @param organCode
	 *            租户编码
	 * @param organLogicId
	 *            租户逻辑主键
	 * @param msgType
	 *            消息类型
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 * @param sendUser
	 *            发送人
	 * @param receiveUser
	 *            接收人
	 * @param openUrl
	 *            打开URL地址，可以为空
	 * @param sendType
	 *            发送类型
	 */
	@Override
	public void pushMsg(final String organCode, final long organLogicId, final String msgType, final String title,
			final String content, final MsgUserVO sendUser, final MsgUserVO receiveUser, final String openUrl,
			final String sendType) {
		final MsgDTO obj = new MsgDTO();
		obj.setOrganCode(organCode);
		obj.setOrganLogicId(organLogicId);
		// 消息标题
		obj.setTitle(title);
		// 消息内容
		obj.setContent(content);
		// 发送类型
		obj.setSendType(sendType);
		// 接收人
		final List<MsgUserVO> receiveUsers = new ArrayList<MsgUserVO>();
		receiveUsers.add(receiveUser);
		obj.setReceiveUsers(receiveUsers);

		if (sendUser != null) {
			// 建立人
			obj.setUserId(sendUser.getUserId());
			obj.setUserName(sendUser.getUserName());
		}

		obj.setUrl(openUrl);
		obj.setType(msgType);

		save(obj);

	}

	/**
	 * 保存
	 *
	 * @param obj
	 *            消息
	 */
	@Override
	public void save(final MsgDTO obj) {
		if (obj == null) {
			return;
		}

		final ApiResponse<Object> result = messageDao.save(obj);

		if (result.getCode() == ApiCode.ERROR.getCode()) {
			Log.error(result.getMessage());
		}
	}

}
